package com.hspedu.homework;

/**
 * @author DL5O
 * @version 1.0
 */
public class Homework02 {
    public static void main(String[] args) {
        Withdraw withdraw = new Withdraw();
        Thread A = new Thread(withdraw);
        Thread B = new Thread(withdraw);
        A.setName("A");
        B.setName("B");
        A.start();
        B.start();
    }
}

class Withdraw  implements Runnable {
    private int money = 10000;
    private boolean loop = true;

    public void deal() {

        //1.这里使用了synchronized 实现了线程同步
        //2.当多个线程执行到这里的时候，就回去争夺 this对象锁
        //3.那个线程执行到 this对象锁，就执行这个代码块，执行玩后，会释放这个锁，准备继续争夺
        //4.争夺不到就阻塞到这里，就blocked
        //5.this 是一个非公平锁

        synchronized (/*Withdraw.class*/this){
            if (money <= 0) {
                loop = false;
                System.out.println("余额不足");
                return;
            }
            money -= 1000;
            System.out.println(Thread.currentThread().getName() + "取走了1000，剩余" + money);
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (loop) {
            deal();
        }
    }
}

